package com.mine.frame.mylandemo.ui.pl

import android.app.Service
import android.content.ComponentName
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.ClickUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.ServiceUtils
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.mine.frame.common.base.BaseActivity
import com.mine.frame.common.empty.EmptyPresenter
import com.mine.frame.common.empty.IEmpty
import com.mine.frame.mylandemo.R
import com.mine.frame.mylandemo.adapter.HomeAdapter
import com.mine.frame.mylandemo.entity.pl.HomeBean
import com.pairlink.connectedmesh.lib.MeshCallback
import com.pairlink.connectedmesh.lib.MeshService
import com.third.device.mg.serialport.utils.send.MGSendUtils
import com.third.device.mg.serialport.utils.send.ProcessEnum
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.schedulers.Schedulers
import io.reactivex.rxjava3.subjects.PublishSubject
import kotlinx.android.synthetic.main.atv_pl_main.*
import java.util.concurrent.TimeUnit

/**
 * @Date 2022/4/18
 * Description:
 */
class PLMainAtv : BaseActivity<IEmpty, EmptyPresenter>(), IEmpty {

    private var listHome = mutableListOf<HomeBean>()

    //流程观察者
    private val ps = PublishSubject.create<HomeBean>()
    private lateinit var psDisposable: Disposable

    private val mAdapter = HomeAdapter()

    override fun initLayoutId(): Int = R.layout.atv_pl_main

    override fun initPresenter(): EmptyPresenter = EmptyPresenter(this)

    override fun initLayoutAfter(savedInstanceState: Bundle?) {
        ServiceUtils.bindService(MeshService::class.java, connectService, Service.BIND_AUTO_CREATE)
        ClickUtils.applySingleDebouncing(arrayOf(btnScanHome)) {
            when (it) {
                btnScanHome -> {
                    MeshService.getInstance().API_scan_homeid(true)
                    stopScan()
                }
            }
        }
        mRecycler.adapter = mAdapter
        mAdapter.setOnItemClickListener({ adapter, view, position ->

        })
    }


    private fun stopScan() {
        Observable.just(0)
            .delay(3, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnNext {
                MeshService.getInstance().API_scan_homeid(false)
                showSuccess("扫描完成")
            }
            .subscribe()
    }


    /**
     * 订阅流程
     */
    private fun subscribeProcess() {
        psDisposable = ps.map { bean ->
            listHome.find {item ->
                item.homeId.equals(bean.homeId)
            }?:let {
                listHome.add(bean)
            }
            listHome
        }.throttleLast(1 ,TimeUnit.SECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe { result ->
                mAdapter.setList(result)
            }

    }



    override fun onDestroy() {
        super.onDestroy()
        ServiceUtils.unbindService(connectService)
        if (!psDisposable.isDisposed){
            psDisposable.dispose()
        }
    }

    private val connectService = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            MeshService.getInstance().mCallback = meshBack
            subscribeProcess()
        }

        override fun onServiceDisconnected(name: ComponentName?) {
        }
    }

    private val meshBack = object : MeshCallback() {
        override fun onHomeidFound(homeid: String?, name: String?, centralAddr: String?) {
            super.onHomeidFound(homeid, name, centralAddr)
            LogUtils.e("homeId:$homeid  name:$name  centralAddr:$centralAddr")
            ps.onNext(HomeBean(homeid ,name ,centralAddr))
        }
    }
}